﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Net.Mail;
using System.Net;
using System.Threading;
using log4net;
using System.Web.Security;

namespace TsCore
{
    public class EmailAlert : Alert
    {
        private Int32 Port { get; set; }
        private String Host { get; set; }
        private String From { get; set; }
        private String To { get; set; }
        private String User { get; set; }
        private String Pass { get; set; }
        private Boolean EnableSSL { get; set; }
        private Semaphore CanAccess { get; set; }
        
        public void SendAlert(Comment comment, TsUser userToNotify)
        {
            this.CanAccess.WaitOne();
            this.To = userToNotify.Email;

            MailMessage mail = new MailMessage(this.From, this.To);
            SmtpClient client = new SmtpClient();
            client.Port = this.Port;
            client.DeliveryMethod = SmtpDeliveryMethod.Network;
            client.EnableSsl = this.EnableSSL;
            client.UseDefaultCredentials = false;
            client.Host = this.Host;
            client.Credentials = new NetworkCredential(this.User, this.Pass);

            mail.Subject = "Notification for: " + userToNotify.Name;
            mail.Body = comment.Text;

            try
            {
                client.Send(mail);
            }
            catch (Exception e)
            {
                LogManager.GetLogger(Membership.GetUser().UserName).Error("Error al enviar una notificacion a: " + userToNotify.Name + "/" + userToNotify.Surname + ": " + userToNotify.Email, e);
            }
            finally
            {
                this.CanAccess.Release();
            }
        }

        public EmailAlert()
        {
            this.Port = Int32.Parse(ConfigurationManager.AppSettings["SMTPPort"].ToString());
            this.Host = ConfigurationManager.AppSettings["SMTPServer"].ToString();
            this.From = ConfigurationManager.AppSettings["MailFrom"].ToString();
            this.User = ConfigurationManager.AppSettings["MailUser"].ToString();
            this.Pass = ConfigurationManager.AppSettings["MailPass"].ToString();

            if ((ConfigurationManager.AppSettings["MailSSL"].ToString()).Equals("true"))
            {
                this.EnableSSL = true;
            }
            else
            {
                this.EnableSSL = false;
            }

            this.CanAccess = new Semaphore(0, 1);
            this.CanAccess.Release();
        }
    }
}
